#include <core/PatternManager.h>
#include <core/utility.h>

namespace qtangram {
    void PatternManager::load() {
	QString path("");
	path = QFileDialog::getOpenFileName(0,"Choose pattern",QString("../data/Tangrams"), "Tangram files (*.qtan)");
	if(path.isEmpty()) return;
	QFile file(path);
	file.open(QIODevice::ReadOnly);
	QDataStream in(&file);
	quint64 check;
	quint16 size, ID;
	bool flip;
	qreal angle;
	QPointF currentPoint;
	QPolygonF polyCurrent;
	Tan t;
	QLinkedList<Tan> tans;
	in >> check >> size;
	if(check != magicNr) QMessageBox::critical(0,"Read error","Old version or not a tangram file!");
	else {
	    for (int i = 0; i < size; ++i) {
		polyCurrent.clear();
		in >> ID >> flip >> angle >> currentPoint >> polyCurrent;
		t.ID = ID;
		t.flip = flip;
		t.angle = angle;
		t.currentPoint = currentPoint;
		t.polyCurrent = polyCurrent;
		tans.push_back(t);
	    }
	    emit patternLoaded(tans);
	}
    }
    void PatternManager::save(const QLinkedList<Tan>& tans) {
	QString fileName("");
	fileName = QFileDialog::getSaveFileName(0,"Save pattern",QString("../data/Tangrams"),"Tangram files (*.qtan)");
	if(fileName.isEmpty()) return;
	if(fileName.indexOf(".qtan") == -1) fileName += ".qtan";
	QFile file(fileName);
	file.open(QIODevice::WriteOnly);
	QDataStream out(&file);
    out << magicNr /* quint64 */ << static_cast<quint16>(tans.size());
    for(auto it = tans.begin(); it != tans.end(); ++it)
	out << (*it).ID //quint16
	<< (*it).flip //bool
	<< (*it).angle //qreal
	<< (*it).currentPoint //QPointF
	<< (*it).polyCurrent; //QPolygonF
    }
}
